<?php
!function_exists('readover') && exit('Forbidden');
@include_once(D_P.'data/bbscache/debate_config.php');
if (!$action) {
	require_once(R_P.'require/credit.php');
	ifcheck($debate_open,'open');
	ifcheck($debate_topicopen,'topicopen');
	ifcheck($debate_gcmtopen,'gcmtopen');
	$postoption = $replyoption = '';
	$_CREDITTYPE = GetCreditType();
	foreach ($_CREDITTYPE as $key => $value) {
		$postselect = $replyselect = '';
		if ($debate_posttype == $key) {
			$postselect = 'SELECTED';
		}
		if ($debate_replytype == $key) {
			$replyselect = 'SELECTED';
		}
		$postoption .= "<option value=\"$key\" $postselect>$value</option>";
		$replyoption .= "<option value=\"$key\" $replyselect>$value</option>";
	}
} elseif ($action=='setting') {
	$config = GetGP('config','P');
	$config['open']			= (int)$config['open'];
	$config['topicopen']	= (int)$config['topicopen'];
	$config['posttype']		= Char_cv($config['posttype']);
	$config['postmoney']	= (int)$config['postmoney'];
	$config['replytype']	= Char_cv($config['replytype']);
	$config['replymoney']	= (int)$config['replymoney'];
	$config['admin']		= Char_cv($config['admin']);
	if ($config['admin']) {
		$newadmin = '';
		$admin_a  = explode(',',$config['admin']);
		foreach ($admin_a as $value) {
			$value = trim($value);
			if ($value) {
				$value = trim($value);
				if ($value && strpos("$newadmin,",",$value,")===false) {
					$rt = $db->get_one("SELECT uid FROM pw_members WHERE username='$value'",MYSQL_NUM);
					if (!$rt[0]) {
						$errorname = $value;
						adminmsg('user_not_exists');
					}
					$newadmin .= ",$value";
				}
			}
		}
		unset($admin_a);
		$config['admin'] = $newadmin ? substr($newadmin,1) : '';
	}
	foreach ($config as $key => $value) {
		if (${'debate_'.$key}!=$value) {
			$key = 'debate_'.$key;
			$db->pw_update(
				"SELECT hk_name FROM pw_hack WHERE hk_name='$key'",
				"UPDATE pw_hack SET hk_value='$value' WHERE hk_name='$key'",
				"INSERT INTO pw_hack(hk_name,hk_value) VALUES ('$key','$value')"
			);
		}
	}
	updatecache_debate();
	adminmsg('operate_success');
} elseif ($action=='setclass') {
	if ($job == 'add') {
		//$basename .= '&action=setclass';
		$cname = Char_cv(GetGP('cname','P'));
		!$cname && adminmsg('colonyset_empty');
		$rt = $db->get_one("SELECT cid FROM pw_debateclass WHERE cname='$cname'",MYSQL_NUM);
		if ($rt[0]) adminmsg('colonyset_same');
		$db->update("INSERT INTO pw_debateclass(cname) VALUES ('$cname')");
		updatecache_dclass();
		adminmsg('operate_success');
	} elseif ($job == 'delete') {
		//$basename .= '&action=setclass';
		$cid = (int)GetGP('cid','P');
		$rt = $db->get_one("SELECT cid FROM pw_debateclass WHERE cid='$cid'",MYSQL_NUM);
		if (!$rt[0]) adminmsg('colonyset_notfind');
		$dids = '';
		$query = $db->query("SELECT did FROM pw_debatethreads WHERE sortid='$cid'");
		while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
			$dids .= ",$rt[0]";
		}
		$db->free_result($query);
		if ($dids) {
			$dids = substr($dids,1);
			$db->update("DELETE FROM pw_debatereplys WHERE did IN ($dids)");
			$db->update("DELETE FROM pw_debatethreads WHERE did IN ($dids)");
		}
		$db->update("DELETE FROM pw_debateclass WHERE cid='$cid'");
		updatecache_dclass();
		adminmsg('operate_success');
	} else {
		$_DCLASS = array();
		$query = $db->query('SELECT * FROM pw_debateclass WHERE 1');
		while ($rt = $db->fetch_array($query)) {
			$_DCLASS[] = $rt;
		}
		$db->free_result($query);
	}
} elseif ($action=='topic') {
	if (!$job) {
		//$basename .= '&action=topic';
		@include_once(D_P.'data/bbscache/debate_class.php');
		$page = (int)GetGP('page');
		$step = (int)GetGP('step');
		$sortid = (int)GetGP('sortid');
		$pages = $classoption = $sqlwhere = $addpage = '';
		foreach ($debateclassdb as $key => $value) {
			$cselect = $sortid==$key ? 'SELECTED' : '';
			$classoption .= "<option value=\"$key\" $cselect>$value</option>";
		}
		$orderby = 'ORDER BY dateline DESC';
		if ($step==2) {
			$sid = (int)GetGP('sid');
			$keyword = trim(Char_cv(GetGP('keyword')));
			if ($keyword) {
				strlen($keyword) < 3  && adminmsg('search_word_limit');
				$addpage = '&keyword='.rawurlencode($keyword);
			}
			if ($sid > 0) {
				@extract($db->get_one("SELECT total,schedid FROM pw_schcache WHERE sid='$sid'"));
				$total = (int)$total;
			} else {
				if ($_POST && !$keyword && !$sortid) {
					adminmsg('no_condition');
				}
				$schline = md5("debateadmin|$keyword|$sortid|debateadmin");
				@extract($db->get_one("SELECT sid,total,schedid FROM pw_schcache WHERE schline='$schline' LIMIT 1"));
				if (!$schedid) {
					$extra = '';
					$db->update("DELETE FROM pw_schcache WHERE schtime<$timestamp-3600");
					if ($sortid) {
						$sqlwhere .= "sortid='$sortid'";
						$extra = ' AND';
					}
					if ($keyword) {
						$keyword = str_replace(array('%','_'),array('\%','\_'),trim($keyword));
						$sqlwhere .= "$extra title LIKE '%$keyword%'";
					}
					!$sqlwhere && adminmsg('operate_error');
					!$db_maxresult && $db_maxresult = 500;
					$limit = "LIMIT $db_maxresult";
					$total = 0;
					$query = $db->query("SELECT did FROM pw_debatethreads WHERE $sqlwhere $orderby $limit");
					while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
						$total++;
						$schedid .= ($schedid ? ',' : '')."$rt[0]";
					}
					$db->free_result($query);
					if ($schedid) {
						$db->update("INSERT INTO pw_schcache(schline,schtime,total,schedid) VALUES ('$schline','$timestamp','$total','$schedid')");
						$sid = $db->insert_id();
					}
				}
			}
			if (!$schedid) adminmsg('search_none');
		} else {
			$rt = $db->get_one('SELECT COUNT(*) FROM pw_debatethreads',MYSQL_NUM);
			$total = $rt[0];
		}
		$page<1 && $page = 1;
		$tid = ($page-1)*$db_perpage;
		$limit = "LIMIT $tid,$db_perpage";
		$sqlwhere && $sqlwhere = "WHERE $sqlwhere";
		$threaddb = array();
		$query = $db->query("SELECT did,sortid,author,title,dateline,isvisible FROM pw_debatethreads $sqlwhere $orderby $limit");
		while ($rt = $db->fetch_array($query)) {
			$rt['sortname'] = $debateclassdb[$rt['sortid']];
			$rt['dateline'] = get_date($rt['dateline'],'Y-m-d');
			$threaddb[] = $rt;
		}
		$db->free_result($query);
		if ($total > $db_perpage) {
			$sortid && $addpage .= "&sortid=$sortid";
			require_once(R_P.'require/forum.php');
			$numofpage = ceil($total/$db_perpage);
			$pages = numofpage($total,$page,$numofpage,"$basename&action=topic&step=2$addpage&");
		}
	} else {
		$selid = GetGP('selid','P');
		if (!$selid = checkselid($selid)) {
			$basename = "javascript:history.go(-1);";
			adminmsg('operate_error');
		}
		@include_once(D_P.'data/bbscache/debate_class.php');
		require_once(H_P.'require/function.php');
		if ($job=='visible') {
			$db->update("UPDATE pw_debatethreads SET isvisible=1 WHERE did IN ($selid)");
		} elseif ($job=='unvisible') {
			$db->update("UPDATE pw_debatethreads SET isvisible=0 WHERE did IN ($selid)");
		} elseif ($job=='delete') {
			$db->update("DELETE FROM pw_debatereplys WHERE did IN ($selid)");
			$db->update("DELETE FROM pw_debatethreads WHERE did IN ($selid)");
		} else {
			adminmsg('operate_error');
		}
		debatesort_cache();
		debateindex_cache();
		adminmsg("operate_success");
	}
} elseif ($action=='cache') {
	//$basename .= '&action=cache';
	if ($job == 'debateclass') {
		updatecache_debate();
		updatecache_dclass();
		adminmsg("operate_success");
	} elseif ($job == 'debatesort') {
		require_once(H_P.'require/function.php');
		debatesort_cache();
		adminmsg("operate_success");
	} elseif ($job == 'debateindex') {
		@include_once(D_P.'data/bbscache/debate_class.php');
		require_once(H_P.'require/function.php');
		debateindex_cache();
		adminmsg("operate_success");
	} elseif ($job == 'debatevote') {
		$times = 0;
		$start = (int)GetGP('start');
		$percount = (int)GetGP('percount');
		$query = $db->query("SELECT did,debatetype,SUM(vote) as sum FROM pw_debatereplys WHERE vote>0 AND debatetype IN(1,2) GROUP BY did,debatetype LIMIT $start,$percount");
		while ($rt = $db->fetch_array($query)) {
			if ($rt['debatetype']==1) {
				$field = 'obrvote';
			} else {
				$field = 'rervote';
			}
			$db->update("UPDATE pw_debatethreads SET $field=$rt[sum] WHERE did='$rt[did]'");
			$times++;
		}
		if ($times==$percount) {
			$next = $start+$percount;
			adminmsg('updatecache_step',EncodeUrl("$basename&action=cache&job=$job&start=$next&percount=$percount"));
		}
		adminmsg("operate_success");
	} elseif ($job == 'debatethread') {
		$times = 0;
		$start = (int)GetGP('start');
		$percount = (int)GetGP('percount');
		$dids = '';
		$query = $db->query("SELECT did FROM pw_debatethreads ORDER BY dateline DESC LIMIT $start,$percount");
		while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
			$dids .= ",$rt[0]";
			$times++;
		}
		$diddb = array();
		if ($dids) {
			$dids = substr($dids,1);
			$didnum = array();
			$query = $db->query("SELECT aid,did,debatetype FROM pw_debatereplys WHERE did IN ($dids) ORDER BY dateline DESC");
			while ($rt = $db->fetch_array($query)) {
				$didnum[$rt['did']][$rt['debatetype']] = (int)$didnum[$rt['did']][$rt['debatetype']];
				if ($didnum[$rt['did']][$rt['debatetype']]<5) {
					$didnum[$rt['did']][$rt['debatetype']]++;
					if (isset($diddb[$rt['did']][$rt['debatetype']]) && !empty($diddb[$rt['did']][$rt['debatetype']])) {
						$diddb[$rt['did']][$rt['debatetype']] .= ','.$rt['aid'];
					} else {
						$diddb[$rt['did']][$rt['debatetype']] = $rt['aid'];
					}
				}
			}
		}
		$db->free_result($query);
		foreach ($diddb as $key => $value) {
			$db->update("UPDATE pw_debatethreads SET typecache='".addslashes(serialize($value))."' WHERE did='$key'");
		}
		if ($times==$percount) {
			$next = $start+$percount;
			adminmsg('updatecache_step',EncodeUrl("$basename&action=cache&job=$job&start=$next&percount=$percount"));
		}
		adminmsg("operate_success");
	}
}
require_once PrintHack('admin');
function updatecache_debate(){
	global $db;
	$configdb = "<?php\r\n";
	$query = $db->query("SELECT hk_name,hk_value FROM pw_hack WHERE hk_name LIKE 'debate\_%'");
	while ($rt = $db->fetch_array($query,MYSQL_NUM)) {
		$configdb .= '$'.key_cv($rt[0])."=".(pw_var_export($rt[1])).";\r\n";
	}
	$configdb .= "?>";
	writeover(D_P.'data/bbscache/debate_config.php',$configdb);
}
function updatecache_dclass(){
	global $db;
	$class = array();
	$query = $db->query('SELECT * FROM pw_debateclass WHERE 1');
	while ($rt = $db->fetch_array($query)) {
		$class[$rt['cid']] = $rt['cname'];
	}
	writeover(D_P.'data/bbscache/debate_class.php',"<?php\r\n\$debateclassdb=".pw_var_export($class).";\r\n?>");
}
?>